"""
订阅管理API路由
"""

from fastapi import APIRouter, HTTPException
from typing import List, Dict, Any

from models.subscription_models import (
    SubscriptionCreateRequest, 
    SubscriptionCheckoutRequest,
    SubscriptionUpdateRequest,
    SubscriptionUpgradeRequest
)
from managers.stripe_manager import StripeManager

router = APIRouter(prefix="/api/subscriptions", tags=["订阅管理"])

# 创建全局的Stripe管理器实例
stripe_manager = StripeManager()


@router.post("/", response_model=Dict[str, Any])
async def create_subscription(request: SubscriptionCreateRequest):
    """创建订阅"""
    return stripe_manager.subscription_service.create_subscription(request)


@router.post("/checkout", response_model=Dict[str, Any])
async def create_subscription_checkout(request: SubscriptionCheckoutRequest):
    """创建订阅支付会话"""
    return stripe_manager.subscription_service.create_subscription_checkout(request)


@router.get("/", response_model=List[Dict[str, Any]])
async def list_subscriptions(limit: int = 100, offset: int = 0):
    """列出所有订阅"""
    return stripe_manager.subscription_service.list_subscriptions(limit, offset)


@router.get("/{subscription_id}", response_model=Dict[str, Any])
async def get_subscription(subscription_id: str):
    """获取订阅信息"""
    subscription = stripe_manager.subscription_service.get_subscription(subscription_id)
    if not subscription:
        raise HTTPException(status_code=404, detail="订阅不存在")
    return subscription


@router.get("/customers/{customer_id}/subscriptions", response_model=List[Dict[str, Any]])
async def get_customer_subscriptions(customer_id: str):
    """获取客户的所有订阅"""
    return stripe_manager.subscription_service.get_customer_subscriptions(customer_id)


@router.put("/{subscription_id}", response_model=Dict[str, Any])
async def update_subscription(subscription_id: str, request: SubscriptionUpdateRequest):
    """更新订阅信息"""
    subscription = stripe_manager.subscription_service.update_subscription(subscription_id, request)
    if not subscription:
        raise HTTPException(status_code=404, detail="订阅不存在")
    return subscription


@router.delete("/{subscription_id}")
async def cancel_subscription(subscription_id: str, cancel_at_period_end: bool = True):
    """取消订阅"""
    subscription = stripe_manager.subscription_service.cancel_subscription(subscription_id, cancel_at_period_end)
    if not subscription:
        raise HTTPException(status_code=404, detail="订阅不存在")
    return {"message": "订阅取消成功"}


@router.post("/{subscription_id}/upgrade", response_model=Dict[str, Any])
async def upgrade_subscription(subscription_id: str, request: SubscriptionUpgradeRequest):
    """升级/降级订阅（切换产品）"""
    subscription = stripe_manager.subscription_service.upgrade_subscription(subscription_id, request)
    if not subscription:
        raise HTTPException(status_code=404, detail="订阅不存在")
    return subscription


@router.post("/{subscription_id}/renew", response_model=Dict[str, Any])
async def renew_subscription(subscription_id: str):
    """续订已取消的订阅"""
    subscription = stripe_manager.subscription_service.renew_subscription(subscription_id)
    if not subscription:
        raise HTTPException(status_code=404, detail="订阅不存在")
    return subscription
